<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\admin\model\Product as ProductModel;
use addons\alioss\controller\Index as IndexOssModel;
use app\admin\model\User;
use app\admin\model\ChatMessage;
use app\admin\model\GroupChat;
use app\admin\model\MpJson;
use app\admin\model\Category;
use app\admin\model\MpType;
use Exception;
use think\Db;

/**
 * 产品管理
 *
 * @icon   fa fa-list
 */
class Product extends Backend
{

    protected $model = null;
    protected $categorylist = [];
    protected $noNeedRight = ['selectpage'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new MpType();
    }

    /**
     * 查看
     */
    public function index()
    {
       

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('title');
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => &$v) {
                $preview_img = MpJson::where(['mp_type_id'=>$v['id']])->column('preview_img');
                if($preview_img){
                    $v['preview_img'] = implode(',',$preview_img);
                }else{
                    $v['preview_img'] = '';
                }
               
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function add_case_s($id = null)
    {
        $row = $this->model->where('id',$id)->find();
        if (!$row) {
            $this->redirect('add_case_index');
            return;
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {

           

            $params = $this->request->post("row/a");
            unset($params['id']);
            try {
                $params['json'] = json_encode($params['json']);
                $params['mp_type_id'] = $id;
                $params['add_time'] = time();
                $result = MpJson::insert($params);  
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error($row->getError());
                }
            } catch (\think\exception\PDOException $e) {
                $this->error($e->getMessage());
            } catch (\think\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {

            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $params['add_time'] = time();
            $params['module'] = implode(',',$params['module']);
            $params['latitude'] = '30.554786';
            $params['longitude'] = '114.216296';
            $params['username'] = '大熊';
            $params['company'] = '湖北苏拉科技有限公司';
            $params['position'] = '运营';
            $params['address'] = '武汉市龙阳时代B座808';
            $params['wx_img'] = 'https://mp.yuxiang123.cn/uploads/20241018/1b2ce478cc93a53845abbc85a967931a.jpg';
            $params['phone'] = '13554694311';
            $params['mail'] = '1359205926@qq.com';
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    //预览图
    public function get_yl_img()
    {

        $list = MpJson::where(['mp_type_id'=>10])->select();

        $type = $this->model->where(['id'=>['>',25]])->select();

        foreach ($type as $v) {
            foreach ($list as $vo) {
                $vo = $vo->toArray();
                unset($vo['id']);
                $vo['mp_type_id'] = $v['id'];
                MpJson::insert($vo);
            }
        }
        die;

        
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if ($params) {
                $bg = $params['beijing_img'];
                if(strpos($bg, 'cn/') !== false){
                    $bgArr = explode('cn/',$bg);
                }else{
                    $bgArr = explode('com/',$bg);
                }
                $bg = $bgArr[1];
                $zt = ROOT_PATH.'public/assets/fonts/Alibaba-PuHuiTi-Regular.ttf';
                $img0 = 'assets/qcode/'.time().rand(1000, 9999).'.png';
                $img1 = 'assets/qcode/'.time().rand(1000, 9999).'.png';
                $img2 = 'assets/qcode/'.time().rand(1000, 9999).'.png';
                $img3 = 'assets/qcode/'.time().rand(1000, 9999).'.png';
                $img4 = 'assets/qcode/'.time().rand(1000, 9999).'.png';
                $img5 = 'assets/qcode/'.time().rand(1000, 9999).'.png';
                $img6 = 'assets/qcode/'.time().rand(1000, 9999).'.png';
                $img7 = 'assets/qcode/'.time().rand(1000, 9999).'.png';
                $img8 = 'assets/qcode/'.time().rand(1000, 9999).'.png';
                $img9 = 'assets/qcode/'.time().rand(1000, 9999).'.png';
                $img10 = 'assets/qcode/'.time().rand(1000, 9999).'.png';
                $json = $params['json'];
                
                for ($k = 0; $k < count($json['content']); $k++) {
                    if($k == 0){
                        $image0 = \think\Image::open($bg);
                        $image0->text($json['content'][$k],$zt,$json['size'][$k],$json['color'][$k],explode(',',str_replace('，', ',', $json['zhou'][$k])))->save($img0);
                    }elseif($k == 1){
                        $image1 = \think\Image::open($img0);
                        $image1->text($json['content'][$k],$zt,$json['size'][$k],$json['color'][$k],explode(',',str_replace('，', ',', $json['zhou'][$k])))->save($img1);
                    }elseif($k == 2){
                        $image2 = \think\Image::open($img1);
                        $image2->text($json['content'][$k],$zt,$json['size'][$k],$json['color'][$k],explode(',',str_replace('，', ',', $json['zhou'][$k])))->save($img2);
                    }elseif($k == 3){
                        $image3 = \think\Image::open($img2);
                        $image3->text($json['content'][$k],$zt,$json['size'][$k],$json['color'][$k],explode(',',str_replace('，', ',', $json['zhou'][$k])))->save($img3);
                    }elseif($k == 4){
                        $image4 = \think\Image::open($img3);
                        $image4->text($json['content'][$k],$zt,$json['size'][$k],$json['color'][$k],explode(',',str_replace('，', ',', $json['zhou'][$k])))->save($img4);
                    }elseif($k == 5){
                        $image5 = \think\Image::open($img4);
                        $image5->text($json['content'][$k],$zt,$json['size'][$k],$json['color'][$k],explode(',',str_replace('，', ',', $json['zhou'][$k])))->save($img5);
                    }elseif($k == 6){
                        $image6 = \think\Image::open($img5);
                        $image6->text($json['content'][$k],$zt,$json['size'][$k],$json['color'][$k],explode(',',str_replace('，', ',', $json['zhou'][$k])))->save($img6);
                    }elseif($k == 7){
                        $image7 = \think\Image::open($img6);
                        $image7->text($json['content'][$k],$zt,$json['size'][$k],$json['color'][$k],explode(',',str_replace('，', ',', $json['zhou'][$k])))->save($img7);
                    }elseif($k == 8){
                        $image8 = \think\Image::open($img7);
                        $image8->text($json['content'][$k],$zt,$json['size'][$k],$json['color'][$k],explode(',',str_replace('，', ',', $json['zhou'][$k])))->save($img8);
                    }elseif($k == 9){
                        $image9 = \think\Image::open($img8);
                        $image9->text($json['content'][$k],$zt,$json['size'][$k],$json['color'][$k],explode(',',str_replace('，', ',', $json['zhou'][$k])))->save($img9);
                    }
                }
                $count = count($json['content']);
                if($count == 1){
                    $res = $img0;
                }if($count == 2){
                    unlink($img0);
                    $res = $img1;
                }if($count == 3){
                    unlink($img0);
                    unlink($img1);
                    $res = $img2;
                }if($count == 4){
                    unlink($img0);
                    unlink($img1);
                    unlink($img2);
                    $res = $img3;
                }if($count == 5){
                    unlink($img0);
                    unlink($img1);
                    unlink($img2);
                    unlink($img3);
                    $res = $img4;
                }if($count == 6){
                    unlink($img0);
                    unlink($img1);
                    unlink($img2);
                    unlink($img3);
                    unlink($img4);
                    $res = $img5;
                }if($count == 7){
                    unlink($img0);
                    unlink($img1);
                    unlink($img2);
                    unlink($img3);
                    unlink($img4);
                    unlink($img5);
                    $res = $img6;
                }if($count == 8){
                    unlink($img0);
                    unlink($img1);
                    unlink($img2);
                    unlink($img3);
                    unlink($img4);
                    unlink($img5);
                    unlink($img6);
                    $res = $img7;
                }if($count == 9){
                    unlink($img0);
                    unlink($img1);
                    unlink($img2);
                    unlink($img3);
                    unlink($img4);
                    unlink($img5);
                    unlink($img6);
                    unlink($img7);
                    $res = $img8;
                }if($count == 10){
                    unlink($img0);
                    unlink($img1);
                    unlink($img2);
                    unlink($img3);
                    unlink($img4);
                    unlink($img5);
                    unlink($img6);
                    unlink($img7);
                    unlink($img8);
                    $res = $img9;
                }
                $filePath = '/www/wwwroot/mingpian/public/'.$res;
                $IndexOssModel = new IndexOssModel();
                $url = $IndexOssModel->bendi_upload($filePath);
                unlink($res);
                $this->success('操作成功',$url);
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
    }

    /**
     * 查看
     */
    public function add_case_index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('title');
            $list = MpType::where($where)
                ->where(['is_sale'=>0,'status'=>1])
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }


    public function add_case($id = null,$type = '')
    {

        $row = $this->model->where('id',$id)->find();
        if (!$row) {
            $this->redirect('add_case_index');
            return;
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    


    //精选
    public function setRecommendTime()
    {
        if ($this->request->isPost()) {
            $data = $this->request->request();
            if(!$data['type']){
                $this->error('参数错误');
            }
            if($data['type'] == 1){
                $recommend_time = time();
            }else{
                $recommend_time = 0;
            }
            $result = ProductModel::where(['id'=>$data['id']])->update(['recommend_time'=>$recommend_time]);
            if ($result !== false) {
                $this->success();
            } else {
                $this->error('操作失败');
            }
        }
    }
    //推送群聊
    public function pushChat()
    {
        if ($this->request->isPost()) {
            $data = $this->request->request();
            $GroupChat = GroupChat::where(['number'=>['>',0]])->select();
            foreach ($GroupChat as $v) {
                $where = [
                    'type'=>3,
                    'goods_id'=>$data['id'],
                    'user_id'=>439,
                    'is_group_chat'=>1,
                    'sort'=>$v['identification'],
                    'add_time'=>time(),
                ];
                ChatMessage::insert($where);
            }
            $this->success();
        }
    }

    //是否联系
    public function setIsContact()
    {
        if ($this->request->isPost()) {
            $data = $this->request->request();
            $result = ProductModel::where(['id'=>$data['id']])->update(['is_contact'=>1]);
            if ($result !== false) {
                $this->success();
            } else {
                $this->error('操作失败');
            }
        }
    }
    
    //上/下架
    public function setStatus()
    {
        if ($this->request->isPost()) {
            $data = $this->request->request();
            if(!$data['id']){
                $this->error('参数错误');
            }
            $result = ProductModel::where(['id'=>$data['id']])->update(['status'=>$data['status']]);
            if ($result !== false) {
                $this->success();
            } else {
                $this->error('操作失败');
            }
        }
    }
   

    /**
     * 编辑
     */
    public function remark($ids = null)
    {
        $row = $this->model->where('id',$ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $row['remark_arr'] = [];
        if($row['remark']){
            $row['remark_arr'] = json_decode($row['remark'],true);
        }
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $res = [
                    'time'=>date('Y-m-d H:i:s',time()),
                    'remark'=>$params['remark']
                ];
                $remark_arr = $row['remark_arr'];
                $remark_arr[] = $res;
                $params['remark'] = json_encode($remark_arr);
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * Selectpage搜索
     *
     * @internal
     */
    public function selectpage()
    {
        return parent::selectpage();
    }



}
